<script setup lang="ts">
import type { DictTable } from '@/types/dict'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ref } from 'vue'
import { addDict } from '@/api/dict/index'
const props = defineProps<{
  dMap: Map<string, string>
  // 刷新
  refresh: () => void
}>()
// 关闭
const emit = defineEmits<{
  (event: 'cDlg'): void
}>()
const addForm = ref<DictTable>({
  path: '',
  type: '',
  name: '',
  description: ''
})
const formRules = ref<FormRules<DictTable>>({
  path: [
    {
      required: true,
      message: '请输入关键字'
    }
  ],
  type: [
    {
      required: true,
      message: '请选择字典类型'
    }
  ],
  name: [
    {
      required: true,
      message: '请输入字典名字'
    }
  ],
  description: [
    {
      required: true,
      message: '请输入字典描述'
    }
  ]
})

// 表单dom
const elFormRef = ref<FormInstance>()
function add() {
  elFormRef.value?.validate((d) => {
    if (d) {
      addDict(addForm.value)
        .then((d) => {
          ElMessage.success(d.msg)
          emit('cDlg')
          props.refresh()
        })
        .catch((d) => {
          ElMessage.error(d.msg)
        })
    }
  })
}
</script>

<template>
  <el-form ref="elFormRef" :model="addForm" :rules="formRules" label-width="150px" width="200px">
    <el-form-item required :label="(dMap.get('name') || 'name') + '：'" prop="name">
      <el-input
        v-model="addForm.name"
        :placeholder="'请输入' + dMap.get('name') || 'name'"
      ></el-input>
    </el-form-item>
    <el-form-item required :label="(dMap.get('type') || 'type') + '：'" prop="type">
      <el-select v-model="addForm.type" :placeholder="'请选择' + dMap.get('type') || 'type'">
        <el-option label="head" value="head"> </el-option>
        <el-option label="val" value="val"> </el-option>
      </el-select>
    </el-form-item>
    <el-form-item required :label="(dMap.get('path') || 'path') + '：'" prop="path">
      <el-input
        v-model="addForm.path"
        :placeholder="'请输入' + dMap.get('path') || 'path'"
      ></el-input>
    </el-form-item>
    <el-form-item
      required
      :label="(dMap.get('description') || 'description') + '：'"
      prop="description"
    >
      <el-input
        v-model="addForm.description"
        type="textarea"
        :placeholder="'请输入' + dMap.get('description') || 'description'"
      ></el-input>
    </el-form-item>
    <div class="buttons">
      <el-button type="primary" @click="emit('cDlg')">取消</el-button>
      <el-button type="success" @click="add">保存</el-button>
    </div>
  </el-form>
</template>
<style scoped lang="less">
.buttons {
  display: flex;
  margin-top: 30px;
  justify-content: flex-end;
}
</style>
